package com.jiyi.activity.datainput.jm;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.datainput.DIBasePicActivity;
import com.jiyi.bean.datainput.DataInputXFLLJSBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.DownloadPicOverInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.widget.picselect.PicSelectConstans;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class DataInputXFLLJSActivity extends DIBasePicActivity implements DownloadPicOverInterface {
	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.is_miniature_fire_station)
	Spinner is_miniature_fire_station;
	@BindView(R.id.etQK)
	EditText etQK;
	@BindView(R.id.etRYQK)
	EditText etRYQK;

	@BindView(R.id.sVerdict)
	Spinner sVerdict;
	@BindView(R.id.etSuggest)
	EditText etSuggest;

	@BindView(R.id.gvPic)
	GridView gvPic;

	ArrayAdapter<String> is_miniature_fire_station_Adapter,
			miniature_fire_station_Adapter, no_miniature_fire_station_Adapter,
			sVerdict_Adapter;

	String build_no;

	// 加载的进度条
	Dialog dialog;

	Map<Integer, String> results = new HashMap<Integer, String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_data_input_xflljs);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	public void init() {
		setTop();
		getIntentData();
		setAdapter();
		getData();
		super.setDownloadPicOverInterface(this);
	}

	private void getIntentData() {
		build_no = getIntent().getStringExtra("build_no");
	}

	private void setTop() {
		tvTitle.setText("消防力量建设");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("保存");
	}

	private void setAdapter() {
		is_miniature_fire_station_Adapter = new ArrayAdapter<String>(this,
				R.layout.item_spinner, getResources().getStringArray(
						R.array.yes_no));
		is_miniature_fire_station.setAdapter(is_miniature_fire_station_Adapter);
		miniature_fire_station_Adapter = new ArrayAdapter<String>(this,
				R.layout.item_spinner, getResources().getStringArray(
						R.array.aqss));

		sVerdict_Adapter = new ArrayAdapter<String>(this,
				R.layout.item_spinner, getResources().getStringArray(
						R.array.verdict));
		sVerdict.setAdapter(sVerdict_Adapter);
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			PicSelectConstans.current.clear();
			PicSelectConstans.publish_pics.clear();
			finish();
			break;
		case R.id.tvSearch:
			downloadImage();
			break;
		default:
			break;
		}
	}



	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("build_info_id", build_no);

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.DATA_INPUT_XFLLJS_READ,
				"", params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								Log.e("dfdsf   ", result);
								DataInputXFLLJSBean temp = new Gson().fromJson(
										data, DataInputXFLLJSBean.class);
								if (temp == null) {
									temp = new DataInputXFLLJSBean();
									temp.setBuild_info_id(build_no);
									temp.setIs_miniature_fire_station(0);
									temp.setMiniature_fire_station("");
									temp.setNo_miniature_fire_station("");
								}
								setData(temp);
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	void setData(DataInputXFLLJSBean temp) {
		is_miniature_fire_station.setSelection(temp
				.getIs_miniature_fire_station());
		etQK.setText(temp.getMiniature_fire_station());
		etRYQK.setText(temp.getNo_miniature_fire_station());
		sVerdict.setSelection(temp.getVerdict());
		etSuggest.setText(temp.getSuggest());

		PicSelectConstans.publish_pics = temp.getImage() == null ? new ArrayList<String>() : temp.getImage();
		refreshAdapter(gvPic);
	}



	@Override
	public void onBackPressed() {
		PicSelectConstans.current.clear();
		PicSelectConstans.publish_pics.clear();
		super.onBackPressed();
	}

	void doPost() {
		String webApi = WebApi.DATA_INPUT_XFLLJS;
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("build_info_id", build_no);
		params.put("is_miniature_fire_station",
				is_miniature_fire_station.getSelectedItemPosition() + "");
		params.put("miniature_fire_station", etQK.getText().toString());
		params.put("no_miniature_fire_station", etRYQK.getText().toString());
		params.put("build_info_id", build_no);
		params.put("verdict", sVerdict.getSelectedItemPosition() + "");
		params.put("suggest", etSuggest.getText().toString());

		PostFormBuilder postForm = OkHttpUtils.post().url(webApi);
		postForm.params(params);
		// 图片数组
		int size = PicSelectConstans.publish_pics.size();
		File file;
		for (int i = 0; i < size; i++) {
			if (PicSelectConstans.publish_pics.get(i).contains("http")) {
				continue;
			}
			file = new File(PicSelectConstans.publish_pics.get(i));
			postForm.addFile("image[]", "pic" + (i + 1) + ".jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						finish();
					} else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg(
								"尚未登录或该用户在其他地方登录，请重新登录！");
						// 清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context,
								true);
						return;
					} else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}

	@Override
	public void post() {
		doPost();
	}
}
